package com.example.bpmn.service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
@RequiredArgsConstructor
public class ProcessService {

    private final RuntimeService runtimeService;

    public String startProcess(String processKey, String businessKey, Map<String, Object> variables) {
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(
            processKey,
            businessKey,
            variables != null ? variables : new HashMap<>()
        );
        
        log.info("流程启动成功: processInstanceId={}", processInstance.getId());
        return processInstance.getId();
    }

    public Map<String, Object> getProcessStatus(String processInstanceId) {
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
            .processInstanceId(processInstanceId)
            .singleResult();
            
        if (processInstance == null) {
            throw new RuntimeException("流程实例不存在: " + processInstanceId);
        }

        Map<String, Object> variables = runtimeService.getVariables(processInstanceId);
        
        return Map.of(
            "processInstanceId", processInstanceId,
            "businessKey", processInstance.getBusinessKey(),
            "status", processInstance.isEnded() ? "COMPLETED" : "RUNNING",
            "variables", variables
        );
    }
} 